#include "StdAfx.h"

Genome::Genome(int l, bool init, double mutRate)
{
	this->_length = l;
	this->_mutationRate = mutRate;

	if(init)
		CreateGenes();
}

Genome::~Genome(void)
{
	delete this->_genes;
}

void Genome::CreateGenes()
{
	srand((unsigned)time(NULL));

	for (int i=0; i< this->_length; i++)
		this->_genes[i] = (double)(rand() ^ (rand() >> 3));
}

void Genome::Crossover(Genome *parent2, Genome *child1, Genome *child2)
{
	srand((unsigned)time(NULL));
	double a = ((double)rand()/(double)RAND_MAX);

	child1 = new Genome(this->_length, false, this->_mutationRate);
	child2 = new Genome(this->_length, false, this->_mutationRate);

	for (int i = 0; i < this->_length; i++) {
		child1->_genes[i] = a * this->_genes[i] + (1.0 - a)*parent2->_genes[i];
		child2->_genes[i] = a * parent2->_genes[i] + (1.0 - a)*this->_genes[i];
    }
}

void Genome::Mutate(int t, int maxT)
{
	srand((unsigned)time(NULL));

	for (int i = 0; i < this->_length; i++) {
		if ((rand()/RAND_MAX) < this->_mutationRate) {
			if(rand() % 2 == 0)
				this->_genes[i] += Delta(t, maxT, (/*UB*/ - this->_genes[i]));
			else
				this->_genes[i] -= Delta(t, maxT, (this->_genes[i] /*- LB*/));
		}
    }
}

double Genome::Delta(int t, int maxT, double y)
{
	double aux = pow( (1.0 - t/maxT), 5);

	return (y * (1 - pow( ((double)rand()/(double)RAND_MAX), aux )));
}